import { assign } from 'lodash'
import rest from '@/utils/rest'
import useRouteUtil from '@/hooks/useRouteUtil'
import { gp } from '@gp'

type Options = {
  res: string
  autoLoad: {
    type: boolean
    default: true
  }
  meta: boolean
  showQuery: boolean
}

export default function (options: Options) {
  const res = options.res
  const autoLoad = options.autoLoad == undefined ? true : options.autoLoad
  const meta = options.meta == undefined ? false : options.meta
  const showQuery = options.showQuery == undefined ? true : options.showQuery

  const route = useRoute()
  const router = useRouter()
  const $baseConfirm = inject('$baseConfirm')
  const $sub: any = inject('$sub')
  const $unsub: any = inject('$unsub')
  const { goUrl } = useRouteUtil()

  const data = reactive({
    list: [],
    meta: {}, // 列表api接口 返回的其他元数据
    query: {},
    pageNo: 1,
    pageSize: 10,
    sortField: '',
    sortOrder: '',
    pageLayout: 'total, sizes, prev, pager, next, jumper',
    loading: false,
    totalCount: 0,
    fold: true,
    showQuery: showQuery,
    selectedRows: [],
  })

  onMounted(async () => {
    if (autoLoad) {
      await loadList()
    }
    if (meta) {
      await loadMeta()
    }
  })

  const loadMeta = async () => {
    const { data: metaData } = await rest.meta(res)
    data.meta = metaData
  }

  const loadList = async (params?: any) => {
    data.loading = true
    let query = data.query
    if (params != undefined) query = params
    const queryParams = assign(
      {
        pageNo: data.pageNo,
        pageSize: data.pageSize,
        sortField: data.sortField,
        sortOrder: data.sortOrder,
      },
      query
    )
    try {
      const {
        data: list,
        totalCount,
        pageSize,
      } = await rest.list(res, queryParams)
      data.list = list
      if (totalCount != undefined) data.totalCount = totalCount
      if (pageSize != undefined) data.pageSize = pageSize
    } catch (error) {
      console.error('请求异常：', error)
    } finally {
      data.loading = false
    }
  }

  function pageNoChange(val: number) {
    debugger
    data.pageNo = val
    loadList()
  }

  function pageSizeChange(val: number) {
    data.pageSize = val
    loadList()
  }

  function sortChange(e: any) {
    console.log(e.order)
    let sort = ''
    if (e.order === 'ascending') {
      sort = 'asc'
    } else if (e.order === 'descending') {
      sort = 'desc'
    }
    console.log(sort)
    if (e.prop.length > 0 && sort.length > 0) {
      data.sortField = e.prop || ''
      data.sortOrder = sort || ''
    }
    loadList()
  }

  function handleFold() {
    data.fold = !data.fold
  }

  function selectionChange(rows: any) {
    data.selectedRows = rows
  }

  function resetQuery() {
    data.query = {}
  }

  function add(params?: any, url?: any) {
    if (url == undefined) url = 'add'

    if (params == undefined) goUrl(url)
    else goUrl(url, { params: encodeURIComponent(JSON.stringify(params)) })
  }

  function edit(params: any, url: any) {
    if (url == undefined) url = 'edit'
    goUrl(url, { params: encodeURIComponent(JSON.stringify(params)) })
  }

  function detail(row: any) {
    const path = route.path
    router.push({
      path: `${path}/detail`,
      query: {
        id: row.id,
        timestamp: new Date().getTime(), //允许同一个详情页同时打开多次，否则会触发路由被缓存下次无法刷新的bug
      },
    })
  }

  const del = async (row: any) => {
    if (row == undefined || row.id == undefined) {
      gp.$baseMessage('待删除行或ID不能为空', 'error', 'vab-hey-message-error')
    }
    const { code } = await rest.delete(res, row.id)
    if (code == 200) {
      gp.$baseMessage('删除成功', 'success', 'vab-hey-message-success')
    }
    await loadList()
  }

  const doOpt = async (url: string, params: any) => {
    if (params == undefined) {
      gp.$baseMessage('操作数据不能为空', 'error', 'vab-hey-message-error')
    }
    const { code } = await rest.req(url, 'post', params)
    if (code == 200) {
      gp.$baseMessage('操作成功', 'success', 'vab-hey-message-success')
    }
    await loadList()
  }

  const exportData = async (url: string, params: any) => {
    const rt = await rest.req(url, 'post', params)
    if (rt.code == 200) {
      gp.$baseMessage('操作成功', 'success', 'vab-hey-message-success')
      window.open(rt.data.url)
    } else {
      gp.$baseMessage(`操作失败：${rt.msg}`, 'error', 'vab-hey-message-error')
    }
  }

  const delSelected = async () => {
    if (data.selectedRows.length <= 0) {
      gp.$baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
      return false
    }

    const ids: any[] = []
    data.selectedRows.forEach((row) => {
      //@ts-ignore
      ids.push(row.id)
    })
    const sIds = ids.join(',')
    //@ts-ignore
    $baseConfirm('你确定要删除选中项吗', null, async () => {
      const { code } = await rest.delete(res, sIds)
      if (code == 200) {
        gp.$baseMessage('删除成功', 'success', 'vab-hey-message-success')
      }
      await loadList()
    })
  }

  // 下级页面触发父页面更新
  $sub('reload-view-data', (path: any) => {
    console.info('refresh data', path, route.path)
    if (path == route.path) {
      loadList()
    }
  })

  onUnmounted(() => {
    $unsub('reload-view-date')
  })

  return {
    data,
    loadList,
    pageNoChange,
    pageSizeChange,
    sortChange,
    handleFold,
    selectionChange,
    resetQuery,
    add,
    edit,
    detail,
    delSelected,
    del,
    doOpt,
    exportData,
  }
}
